package com.ttb.blocksms;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.ttb.bubbles.HelloBubblesActivity;
import com.ttb.bubbles.OneComment;
import com.ttb.database.Blocker;
import com.ttb.database.BlockerDAO;
import com.ttb.database.Contact;
import com.ttb.database.ContactDAO;
import com.ttb.database.MessageDAO;
import com.ttb.database.MessageSMS;
import com.ttb.database.Schedule;
import com.ttb.database.ScheduleDAO;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.sax.StartElementListener;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class BlockService extends BroadcastReceiver {
	private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	private static final String SCHEDULE_SMS = "com.ttb.smshelper.SCHEDULE_SMS";
	private Boolean block = false;
	public static final String ONE_TIME = "onetime";
    public static final int MESSAGE_TYPE_INBOX = 1;
    public static final int MESSAGE_TYPE_SENT = 2;
    
    public static final int MESSAGE_IS_NOT_READ = 0;
    public static final int MESSAGE_IS_READ = 1;
    
    public static final int MESSAGE_IS_NOT_SEEN = 0;
    public static final int MESSAGE_IS_SEEN = 1;
    
    public static final String CONTACT_ID = "contact_id";
    public static final String SMS_BODY = "sms_body";
	@Override
	public void onReceive(Context context, Intent intent) {
		// ---get the SMS message passed in---
		if (intent.getAction().equals(SMS_RECEIVED)) {

			Bundle bundle = intent.getExtras();
			SmsMessage[] msgs = null;
			String str = "";
			if (bundle != null) {
				// ---retrieve the SMS message received---
				Object[] pdus = (Object[]) bundle.get("pdus");
				msgs = new SmsMessage[pdus.length];
				for (int i = 0; i < msgs.length; i++) {
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
					BlockerDAO blockerDAO = new BlockerDAO(context);
					MessageDAO messageDAO = new MessageDAO(context);
					ContactDAO contactDAO = new ContactDAO(context);
					String address = msgs[i].getOriginatingAddress();
					Blocker blocker = blockerDAO.getBlockerFromValueType(
							address, "NUMBER_PHONE");
					
					if (blocker.getValue() != null)
					{
						block = true;
					}
					SmsMessage message = msgs[i];
					contactDAO.open();
					Contact contact = contactDAO.getContactWithPhone(message.getOriginatingAddress());
					contactDAO.close();
					if(contact.getName() != null && !block)
					{
						MessageSMS sms = new MessageSMS();
						sms.setAddress(message.getOriginatingAddress());
						sms.setDate(message.getTimestampMillis());
						sms.setStatus(message.getStatus());
						sms.setRead(MESSAGE_IS_NOT_READ);
						sms.setBody(message.getDisplayMessageBody());
						sms.setSeen(MESSAGE_IS_NOT_SEEN);
						sms.setType(MESSAGE_TYPE_INBOX);
						messageDAO.addMessage(sms);
						if(HelloBubblesActivity.thisActivity != null)
						{
							Intent in = new Intent("SmsMessage.intent.MAIN");
							in.putExtra(SMS_BODY, message.getDisplayMessageBody());
							in.putExtra(CONTACT_ID, contact.getId());
							context.sendBroadcast(in);
						}
						block = true;
					}
				}
				// ---display the new SMS message---
				//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
			}
			if (block) {
				abortBroadcast();
			}
		}
		if (intent.getAction().equals(SCHEDULE_SMS)) {
			PowerManager pm = (PowerManager) context
					.getSystemService(Context.POWER_SERVICE);
			PowerManager.WakeLock wl = pm.newWakeLock(
					PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
			// Acquire the lock
			wl.acquire();

			// You can do the processing here update the widget/remote views.
			Bundle extras = intent.getExtras();
			StringBuilder msgStr = new StringBuilder();
			
			if (extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)) {
				msgStr.append("One time Timer : ");
			}
			Format formatter = new SimpleDateFormat("hh:mm:ss a");
			msgStr.append(formatter.format(new Date()));
			long id = Long.parseLong(extras.getString("ID"));
			Log.d("Task id :", extras.getString("ID"));
			Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
			Log.d("RECIVED :", msgStr.toString());
	        //send message
	    	 String SENT = "SMS_SENT";
	         String DELIVERED = "SMS_DELIVERED";
	  
	         PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
	             new Intent(SENT), 0);
	  
	         PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
	             new Intent(DELIVERED), 0);
	         //get schedule information
	         ScheduleDAO dao = new ScheduleDAO(context);
	         dao.open();
	         Schedule schedule = dao.getSchedule(id);
	         dao.close();
	         //send message
			SmsManager sms = SmsManager.getDefault();
			String number_phone = schedule.getNumberPhoneList();
			String message = schedule.getMessage();
	        sms.sendTextMessage(number_phone, null, message, sentPI, deliveredPI); 
			//Release the lock
			wl.release();
		}

	}
	public void SetAlarm(Context context , Schedule schedule)
    {
        AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context,BlockService.class);
        intent.setAction(SCHEDULE_SMS);
        long scheduleId = schedule.getId();
        intent.putExtra("ID",String.valueOf(scheduleId));
  		Log.d("Time set : ", String.valueOf(scheduleId));
        PendingIntent pi = PendingIntent.getBroadcast(context, (int)scheduleId, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        String interval = schedule.getInterval();
        if(interval == "Once")
        {
        	am.set(AlarmManager.RTC_WAKEUP, schedule.getTriggerTime(), pi);
        }else if(interval == "Daily")
        {
        	am.setRepeating(AlarmManager.RTC_WAKEUP, schedule.getTriggerTime(), AlarmManager.INTERVAL_DAY, pi);
        }else if(interval == "Weekly")
        {
        	
        }else if(interval == "Monthly")
        {
        	
        }else if(interval == "Yearly")
        {
        	
        }
    }

    public void CancelAlarm(Context context,int id)
    {
        Intent intent = new Intent(context, BlockService.class);
        intent.setAction(SCHEDULE_SMS);
        PendingIntent sender = PendingIntent.getBroadcast(context, id, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
  
	
}
